package com.rn_demo3.util;

import android.util.Base64;

import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;

import javax.crypto.BadPaddingException;
import javax.crypto.Cipher;
import javax.crypto.IllegalBlockSizeException;
import javax.crypto.NoSuchPaddingException;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;

public class DecodeUtil {

    //data为待解密的数据，keyBytes为加密时所使用的密钥，transform为加密时所采取的加密模式和填充模式
    public static byte[] decryptData(byte[] data,String password){
        byte[] clearData = null;
        byte[] keyBytes = password.getBytes();

        SecretKeySpec secretKeySpec = new SecretKeySpec(keyBytes,"AES");

        try {

            //根据格式获取Cipher实例，需与加密时一致
            Cipher cipher = Cipher.getInstance("AES");
            //初始化Cipher，注意这里变为解密模式
            cipher.init(Cipher.DECRYPT_MODE,secretKeySpec);
            //先Base64解码
            byte[] temp = Base64.decode(data,Base64.DEFAULT);

            //解密数据
            clearData = cipher.doFinal(temp);

        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        } catch (NoSuchPaddingException e) {
            e.printStackTrace();
        } catch (InvalidKeyException e) {
            e.printStackTrace();
        } catch (BadPaddingException e) {
            e.printStackTrace();
        } catch (IllegalBlockSizeException e) {
            e.printStackTrace();
        }

        return clearData;

    }

    // 解密
    public static String decrypt(byte[] sSrc, String sKey) throws Exception {
        try {
            byte[] raw = sKey.getBytes("ASCII");
            SecretKeySpec skeySpec = new SecretKeySpec(raw, "AES");
            Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
            cipher.init(Cipher.DECRYPT_MODE, skeySpec);
            byte[] encrypted1 =  Base64.decode(sSrc,Base64.NO_WRAP);//先用base64解密
            byte[] original = cipher.doFinal(encrypted1);
            String originalString = new String(original,"utf-8");
            return originalString;
        } catch (Exception ex) {
            return null;
        }
    }

}
